package com.xuecheng.client.sdk.client;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.xuecheng.client.sdk.enums.CodeEnums;
import com.xuecheng.client.sdk.rsp.BaseSdkResponse;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import static com.xuecheng.client.sdk.utils.SignUtils.genSign;

/**
 * 开放api客户端sdk
 */
@Slf4j
public class XueChengClient {

    private final String gatewayHost;

    private final String accessKey;

    private final String secretKey;

    public XueChengClient(String accessKey, String secretKey,String gatewayHost) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
        this.gatewayHost = gatewayHost;
    }
    public BaseSdkResponse getCourseBaseInfo(String requestJson) {

        //请求参数校验
        if(Objects.isNull(requestJson)){
            return new BaseSdkResponse().setCode(CodeEnums.REQ_PARAM_ERROR.getCode()).setMsg(CodeEnums.REQ_PARAM_ERROR.getDesc());
        }

        HttpResponse httpResponse = HttpRequest.post(gatewayHost + "/open/content/course")
                .addHeaders(getHeaderMap(requestJson))
                .body(requestJson)
                .execute();

        //请求是否成功
        if(!httpResponse.isOk()){
            log.error("请求不成功{}",httpResponse.toString());
            return BaseSdkResponse.reqParamError().setCode(CodeEnums.REQ_ERROR.getCode()).setMsg(CodeEnums.REQ_ERROR.getDesc());
        }

        return parseRsp(httpResponse.body());
    }

    /**
     * 解析响应
     * @param body
     * @return
     */
    private BaseSdkResponse parseRsp(String body){
        return JSON.parseObject(body, BaseSdkResponse.class);
    }

    /**
     * API签名认头部添加
     * @param body
     * @return
     */
    private Map<String, String> getHeaderMap(String body) {
        Map<String, String> hashMap = new HashMap<>();
        hashMap.put("accessKey", accessKey);
        // 一定不能直接发送
        // hashMap.put("secretKey", secretKey);
        hashMap.put("nonce", RandomUtil.randomNumbers(4));
        hashMap.put("body", body);
        hashMap.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
        hashMap.put("sign", genSign(body, secretKey));
        return hashMap;
    }

}
